package com.mall.controller;

import com.domain.User;
import com.domain.result.ResultData;
import com.mall.AESUtil;
import com.service.seinterface.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/mall")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public ResultData login(String username,String password){
        ResultData resultData=new ResultData();
        try {
            User user=userService.selectByUsername(username);
            String password2MD5 = AESUtil.encrypt(password,AESUtil.PASSWORD);
            if (password2MD5.equals(user.getPassword())) {
                UsernamePasswordToken token = new UsernamePasswordToken(username, password2MD5);
                Subject subject = SecurityUtils.getSubject();
                subject.getSession().setTimeout(5000);  //修改会话有效时间 单位:ms
                try {
                    subject.login(token);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            List<User> loginuser=userService.login(username,password2MD5);
            if(loginuser==null||loginuser.size()==0){
                resultData.setResult(1);
            }else{
                resultData.setData(loginuser);
            }
        } catch (InvalidSessionException e) {
            e.printStackTrace();
            resultData.setResult(1);
        }

        return resultData;
    }


    @RequestMapping("/addUser")
    public ResultData addUser(@RequestBody User user){
        return  userService.addUser(user);
    }

    @RequestMapping("/selectAll")
    public ResultData selectAll(){
        return userService.selectAll();
    }


    @RequestMapping("/deleteUser")
    public ResultData deleteUserById(String userid){
        return userService.deleteUserById(userid);
    }


    @RequestMapping("updateUser")
    public ResultData updateUserById(@RequestBody User user){
        return  userService.updateUserById(user);
    }
}
